import { All, BadGatewayException, Body, Controller, Get, Query, Redirect, Req } from '@nestjs/common';
import { ModelType } from '@typegoose/typegoose/lib/types';
import { InjectModel } from 'nestjs-typegoose';
import { QudaobaoModel } from './mongodb/models/qudaobaoModel/qudaobaoModel';
import { RedisdbService } from './redis/redisdb.service';
import axios from 'axios';


@Controller()
export class AppController {


  constructor(
    private redis: RedisdbService,
    @InjectModel(QudaobaoModel) private readonly channel: ModelType<QudaobaoModel>,
  ) { }


  @Get()
  getHello(): string {
    return '连接成功';
  }



  @Get('tiaozhuan')
  async tiaozhuan(@Query() query) {
    try {
      const reslut = await this.channel.findOne({ mark: query.mark }, ['tiaozhuan', 'tiaourl', 'webmodel']);
      if (reslut.tiaozhuan) {
        return { data: true, tiaourl: reslut.tiaourl };
      }
      else {
        if (reslut.webmodel) {
          return { data: false, isNew: true };
        }
        return { data: false, isNew: false };
      }
    }
    catch (error) {
      throw new BadGatewayException(error)
    }
  }



  @Get('kehulist')
  async kehulist(@Query() query, @Req() req) {
    let ditch = parseInt(req.headers.origin.match(/\/\/(\d*)/)[1]);
    try {
      if (query.kehuyuming) {
        const reslut = await axios.get(query.kehuyuming + '/api/chat/list', {
          params: {
            page: 1,
            page_size: 5,
            visiter_id: query.visiter_id,
            business_id: 1
          }
        });
        let kflist = [];
        reslut.data.data.forEach(element => {
          element.service.avatar = query.kehuyuming + element.service.avatar;
          element.url = query.kehuyuming + `/index/index/home/business_id/1/special/${element.service_id}/visiter_id/${element.visiter_id}/visiter_name/${ditch}号包访客_${element.visiter_id.slice(-6)}/post_id/165.html`;
          kflist.push(element);
        });
        return { code: 200, data: kflist };
      }
      else {
        return { code: 500, msg: '未配置客服系统' };
      }
    }
    catch (error) {
      throw new BadGatewayException(error)
    }
  }



  @Get('unread')
  async unread(@Query() query) {
    try {
      if (query.kehuyuming) {
        const reslut = await axios.get(query.kehuyuming + '/api/chat/unread', {
          params: {
            visiter_id: query.visiter_id,
            timestamp: Math.floor(Date.now() / 1000)
          }
        });
        return { code: 200, data: reslut.data.data };
      }
      else {
        return { code: 500, msg: '未配置客服系统' };
      }
    }
    catch (error) {
      throw new BadGatewayException(error)
    }
  }


  @Get('yszc')
  @Redirect()
  getyszc() {
    return { url: 'public/yszc.html' };
  }





  /* 趣头条 */
  //    /qudao?ditch=1&imei=__IMEIMD5__&callback=__CALLBACK_URL__&oaid=__OAID__&idfa=__IDFA__&ip=__IP__

  /* 聚流包-触宝 */
  //    /qudao?ditch=1&imei=${IMEI_MD5}&callback=${CLICKID}&oaid=${OAID}&idfa=${IDFA}&ip=${IP}

  /* 有道 */
  //    /qudao?ditch=1&imei=__imei__&callback=__conv__&oaid=__oaid__&idfa=__idfa__&ip=__ip__

  /* 东方头条 */
  //    /qudao?ditch=1&imei=__IMEI__&callback=__CALLBACK_URL__&oaid=__OAID__&idfa=__IDFA__&ip=__IP__&ts=__TS__&an=__ANDROIDID__

  // 快手
  //   /qudao?ditch=1&imei=__IMEI2__&callback=__CALLBACK__&oaid=__OAID__&idfa=__IDFA3__&ip=__IP__

  //喜马拉雅
  //   /qudao?ditch=1&imei=_IMEI_MD5_&callback=_CALLBACK_URL_&oaid=_OAID_&idfa=_IDFA_&ip=_IP_

  //知乎
  //   /qudao?ditch=1&imei=__IMEI__&callback=__CALLBACK__&oaid=__OAID__&idfa=__IDFA__&ip=__IP__

  //抖音
  //   /qudao?ditch=1&imei=__IMEI__&callback=__CALLBACK_URL__&oaid=__OAID__&idfa=__IDFA__&ip=__IP__&androidid=__ANDROIDID__

  //刷宝
  //   /qudao?ditch=1&imei={device_id}&callback={callback_url}&oaid={oaid}&idfa={device_id}&ip={ip}

  //乐游
  //   /qudao?ditch=1&imei={imei_md5}&callback={callback}&oaid={oaid}&idfa={idfa}&ip={ip}

  //广点通
  //  /qudao?ditch=60&access_token=29cf6b69dbf7d41100e4cff4dab37c1e&account_id=20529045&user_action_set_id=1111902064

  //Bilibili
  //   /qudao?ditch=1&imei=__IMEI__&callback=__CALLBACKURL__&oaid=__OAID__&idfa=__IDFA__&ip=__IP__

  //搜狗
  //   /qudao?ditch=1&imei={{IMEI_MD5}}&callback={{CALLBACK_URL}}&oaid={{OAID}}&idfa={{IDFA}}&ip={{IP}}

  //百度
  //   /qudao?ditch=1&imei={{IMEI_MD5}}&callback={{CALLBACK_URL}}&oaid={{OAID}}&idfa={{IDFA}}&ip={{IP}}

  //新浪
  //   /qudao?ditch=1&imei={User}&oaid={Oaid}&ip={Ip}&callback={Uuid}&cnv_id=转化ID 可在新建转化时取到&token=token 可在新建转化时取到

  //UC
  //   /qudao?ditch=1&imei={IMEI_SUM}&callback={CALLBACK_URL}&oaid={OAID}&ip={IP}&ts={TS}


  @All('qudao')
  async qutoutiao(@Query() query, @Body() body) {
    const isQuery = Object.keys(query);
    const isBody = Object.keys(body);

    try {
      let content: any = {}
      if (isQuery.length != 0) {
        content = query
      }
      if (isBody.length != 0) {
        content = body
      }
      if (!content.ips) {
        if (content.imei || content.muid) {
          await this.redis.set((content.imei || content.muid).toLowerCase() + "_" + content.ditch, content, 60 * 60 * 24 * 3);
        }
        if (content.oaid) {
          await this.redis.set(content.oaid.toLowerCase() + "_" + content.ditch, content, 60 * 60 * 24 * 3);
        }
        if (content.idfa) {
          await this.redis.set(content.idfa.toLowerCase() + "_" + content.ditch, content, 60 * 60 * 24 * 3);
        }
      } else {
        if (content.ip) {
          await this.redis.set(content.ip.toLowerCase() + "_" + content.ditch, content, 60 * 60 * 24 * 3);
        }
      }
      return { status: 1 };
    }
    catch (error) {
      console.log(error);
      throw new BadGatewayException(error)
    }
  }





}




